﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenCLNet;

namespace GPUTracer
{
    [Serializable]
    public class Triangle : Object
    {
        private Float4 _p1;
        private Float4 _p2;
        private Float4 _p3;

        public Triangle(Float4 p1, Float4 p2, Float4 p3, SurfaceType surface = SurfaceType.Checkerboard)
        {
            _p1 = p1;
            _p2 = p2;
            _p3 = p3;
            _surface = surface;
        }

        public Float4 P1
        {
            get { return _p1; }
        }

        public Float4 P2
        {
            get { return _p2; }
        }

        public Float4 P3
        {
            get { return _p3; }
        }

        public override byte[] ToBinary()
        {
            var result = new byte[64];
            int c = 0;

            Helper.Float4ToByteArray(result, P1, ref c);   //position
            Helper.Float4ToByteArray(result, P2, ref c);   //position
            Helper.Float4ToByteArray(result, P3, ref c);   //position
            result[c] = 2;                      //type
            result[c+1] = (byte)Surface;        //surface

            return result;
        }

        public override string ToString()
        {
            return string.Format("Triangle - P1: ({0}, {1}, {2}) - P2: ({3}, {4}, {5}) - P3: ({6}, {7}, {8})", 
                                        P1.S0, P1.S1, P1.S2, P2.S0, P2.S1, P2.S2, P3.S0, P3.S1, P3.S2);
        }

        public override BoundingBox? GetBoundingBox()
        {
            var minX = P1.S0 < P2.S0 ? P1.S0 : P2.S0;
            minX = minX < P3.S0 ? minX : P3.S0;
            var minY = P1.S1 < P2.S1 ? P1.S1 : P2.S1;
            minY = minY < P3.S0 ? minY : P3.S1;
            var minZ = P1.S2 < P2.S2 ? P1.S2 : P2.S2;
            minZ = minZ < P3.S2 ? minZ : P3.S2;

            var maxX = P1.S0 > P2.S0 ? P1.S0 : P2.S0;
            maxX = maxX > P3.S0 ? maxX : P3.S0;
            var maxY = P1.S1 > P2.S1 ? P1.S1 : P2.S1;
            maxY = maxY > P3.S1 ? maxY : P3.S1;
            var maxZ = P1.S2 > P2.S2 ? P1.S2 : P2.S2;
            maxZ = maxZ > P3.S2 ? maxZ : P3.S2;
            
            var min = new Float4(minX, minY, minZ, 0);
            var max = new Float4(maxX, maxY, maxZ, 0);

            return new BoundingBox(min, max);
        }
    }
}
